package com.yunzhou.service.impl;

import com.yunzhou.properties.MinioProperties;
import com.yunzhou.service.MinioService;
import io.minio.*;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
public class MinioServiceImpl implements MinioService {

    @Resource
    private MinioClient minioClient;
    @Resource
    private MinioProperties minioProperties;

    @Override
    public String uploadFile(MultipartFile file, String bucketName, String fileName) throws Exception {
        // 1、先判断bucket是否存在，不存在需要创建
        if (!minioClient.bucketExists( BucketExistsArgs.builder().bucket(bucketName).build() )) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());

            // 2、创建存储桶时，设置存储桶中的文件访问策略，公开的读
            String policyJsonString = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"PublicRead\",\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"*\"},\"Action\":[\"s3:GetObject\"],\"Resource\":[\"arn:aws:s3:::" + bucketName + "/*\"]}]}";
            minioClient.setBucketPolicy(SetBucketPolicyArgs.builder()
                    .bucket(bucketName)
                    .config(policyJsonString) // json串，里面是访问策略
                    .build());
        }

        // 3、上传文件到该存储桶
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(bucketName)
                .object(fileName)
                .stream(file.getInputStream(), file.getSize(), -1) // 最后一个参数是缓冲区大小，给-1让其自己决定
                .build());

        // 4、返回文件在minio中的URL
        return minioProperties.getEndpoint() + "/" + bucketName + "/" + fileName;

    }

    @Override
    public GetObjectResponse downloadFile(String bucketName, String objectName) throws Exception {
        return minioClient.getObject(GetObjectArgs.builder()
                .bucket(bucketName)
                .object(objectName)
                .build());
    }

}
